package com.sim.web;

import com.sim.util.LogHelper;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpRequest {
    private static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(50, TimeUnit.SECONDS)//设置读取超时时间
            .retryOnConnectionFailure(true)
            .build();

    private static final String JSON_MEDIA_TYPE = "application/json; charset=utf-8";
    private static final String TEXT_MEDIA_TYPE = "text/plain";

    public static Response getResponse(String url) throws Exception {
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        Response response = call.execute();

        return response;
    }

    public static String getResponseString(String url) throws Exception {
//        LogHelper.log("getResponseString url : " + url);
        Response rep = getResponse(url);
        if (rep != null) {
            return rep.body().string();
        }
        return null;
    }

    public static String post(String url, Map<String, String> params) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            bodyBuilder.add(entry.getKey(), entry.getValue());
        }
        try {
            FormBody body = bodyBuilder.build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest post Exception", e);
        }
        return null;
    }

    public static ResponseBody postJson(String url, String strContent) {
        Response response = postStringByJson(url, strContent);
        if(response != null){
            return response.body();
        }
        return null;
    }

    public static String postJsonString(String url, String strContent) {
        ResponseBody body = postJson(url,strContent);
        try {
            if(body!=null){
                return body.string();
            }
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postJsonString Exception", e);
        }
        return null;
    }

    public static Response postStringByJson(String url, String strContent) {
        LogHelper.log("postStringByJson url : " + url);
        LogHelper.log("postStringByJson : " + strContent);
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(
                            MediaType.parse(JSON_MEDIA_TYPE),
                            strContent))
                    .build();
            Response response = client.newCall(request).execute();
            LogHelper.log("request = " + request.toString());
            return response;
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postStringByJson Exception", e);
        }
        return null;
    }

    public static String postJsonText(String url, String strContent) {
        ResponseBody body = postTextBody(url,strContent);
        try {
            if(body!=null){
                return body.string();
            }
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postJsonByte Exception", e);
        }
        return null;
    }

    public static ResponseBody postTextBody(String url, String strContent) {
        Response response = postText(url, strContent);
        if(response != null){
            return response.body();
        }
        return null;
    }

    public static Response postText(String url, String strContent) {
        LogHelper.log("postByte url : " + url);
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(
                            MediaType.parse(TEXT_MEDIA_TYPE),
                            strContent))
                    .build();
            Response response = client.newCall(request).execute();
            LogHelper.log("request = " + request.toString());
            return response;
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postByte Exception", e);
        }
        return null;
    }


    public static Response getDownload(String url) throws Exception {
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        Response response = call.execute();

        return response;
    }

    public static String postHeaderString(String url, String strContent, Map<String,String> headers) {
        ResponseBody body = postHeader(url,strContent, headers);
        try {
            if(body!=null){
                return body.string();
            }
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postJsonString Exception", e);
        }
        return null;
    }

    public static ResponseBody postHeader(String url, String strContent, Map<String,String> headers) {
        Response response = postStringHeader(url, strContent, headers);
        if(response != null){
            return response.body();
        }
        return null;
    }

    public static Response postStringHeader(String url, String strContent, Map<String,String> headers) {
        LogHelper.log("postStringHeader url : " + url);
        LogHelper.log("postStringHeader : " + strContent);
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .headers(createHeaders(headers))
                    .post(RequestBody.create(
                            MediaType.parse(JSON_MEDIA_TYPE),
                            strContent))
                    .build();
            Response response = client.newCall(request).execute();
            LogHelper.log("request = " + request.toString());
            return response;
        } catch (Exception e) {
            LogHelper.log("OkHttpRequest postStringByJson Exception", e);
        }
        return null;
    }

    private static Headers createHeaders(Map<String, String> headersMap) {
        Headers.Builder newHeaders = new Headers.Builder();
        for (Map.Entry<String, String> header : headersMap.entrySet()) {
            newHeaders.add(header.getKey(), header.getValue());
        }
        return newHeaders.build();
    }
}
